package cn.edu.sdjzu.xg.bysj.controller.basic;

import cn.edu.sdjzu.xg.bysj.domain.GraduateProject;
import cn.edu.sdjzu.xg.bysj.service.GraduateProjectCacheService;
import cn.edu.sdjzu.xg.bysj.service.GraduateProjectService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import lombok.extern.slf4j.Slf4j;
import util.Condition;
import util.ControllerHelper;
import util.JSONUtil;
import util.Pagination;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Collection;
import java.util.List;

@Slf4j
@WebServlet("/graduateProject.ctl")
public class GraduateProjectController extends HttpServlet {
    /**
     * GET, http://localhost:8080/graduateProject.ctl?id=1, 查询id=1的项目
     * GET, http://localhost:8080/graduateProject.ctl, 查询所有的项目
     * 把一个或所有类别对象响应到前端
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */

    @Override
    protected void doGet(HttpServletRequest request,
                         HttpServletResponse response)
            throws ServletException, IOException {
        //读取参数id
        String id_str = request.getParameter("id");
        //将request body转换为JSON字串
        String req_jsonStr = JSONUtil.getJSON(request);
        //将request body解析为JSONObject对象
        JSONObject req_jsonObj = JSON.parseObject(req_jsonStr);
        //创建JSON对象respMessage_jsonObj，以便往前端响应信息
        JSONObject respMessage_jsonObj = new JSONObject();
        //如果请求body为空
        if (req_jsonObj == null && id_str == null) {
            respMessage_jsonObj.put("message","未收到请求信息！");
            response.getWriter().println(respMessage_jsonObj);
            return;
        }
        try {
            //如果id_str != null, 说明请求数据有id键，是请求某个对象
            if (id_str != null) {
                int id = Integer.parseInt(id_str);
                responseGP(id, response);
            } else {//请求中包含条件和分页信息，需要响应多个对象
                //读取分页信息，形成分页对象
                //从JSONObject对象中读取 “pagination” 键对应的值(JSONObject对象)
                Pagination pagination = ControllerHelper.getPagination(req_jsonObj);
                //从请求JSONObject对象中读取键“conditionList”对应的值(描述查询条件的JSONArray对象)
                List<Condition> conditionList = ControllerHelper.getConditions(req_jsonObj);
                //响应多个信息，其中conditionList, pagination两个对象引用为空是可能的
                this.responseGPs(response, conditionList, pagination);
            }
        } catch (SQLException e) {
            respMessage_jsonObj.put("message", "数据库操作异常");
            //响应respMessage_jsonObj到前端
            response.getWriter().println(respMessage_jsonObj);
            log.error(e.getMessage());
        } catch (Exception e) {
            respMessage_jsonObj.put("message", "网络异常");
            //响应respMessage_jsonObj到前端
            response.getWriter().println(respMessage_jsonObj);
            //打印异常栈，方便调试
            log.error(e.getMessage());
        }
    }

    //按分页信息响应符合条件的对象和对象总数
    private void responseGPs(HttpServletResponse response,
                              List<Condition> conditionList_json_str,
                              Pagination pagination)
            throws ServletException, IOException, SQLException {
        //分页获得满足条件的所有对象
        Collection<GraduateProject> graduateProjects=
                GraduateProjectService.getInstance().findAll(conditionList_json_str, pagination);
        //第二个参数可以防止循环引用
        String graduateProject_jsonStr = JSON.toJSONString(graduateProjects,
                SerializerFeature.DisableCircularReferenceDetect);
        //创建JSON对象resp_jsonObj，以便往前端响应综合信息
        JSONObject resp_jsonObj = new JSONObject();
        resp_jsonObj.put("totalNum", pagination.getTotalNum());
        resp_jsonObj.put("data", graduateProject_jsonStr);
        //响应resp_jsonObj到前端0
        response.getWriter().println(resp_jsonObj);

    }
    //响应一个对象
    private void responseGP(int id, HttpServletResponse response)
            throws ServletException, IOException, SQLException {
        //根据id查找
        GraduateProject graduateProject =
                GraduateProjectService.getInstance().find(id);
        String graduateProject_jsonStr = JSON.toJSONString(graduateProject);
        //响应到前端
        response.getWriter().println(graduateProject_jsonStr);
    }

    /**
     * POST, http://localhost:8080/graduateProject.ctl, 增加项目
     * 增加一个项目对象：将来自前端请求的JSON对象，增加到数据库表中
     * @param request 请求对象
     * @param response 响应对象
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String graduateProject_json = JSONUtil.getJSON(request);
        JSONObject req_jsonObj = JSON.parseObject(graduateProject_json);
        //将JSON字串解析为对象
        GraduateProject graduateProjectToAdd =
                JSON.parseObject(graduateProject_json,GraduateProject.class);
        System.out.println(graduateProjectToAdd);
        //请求中包含条件和分页信息，需要响应多个对象
        //读取分页信息，形成分页对象
        //从JSONObject对象中读取 “pagination” 键对应的值(JSONObject对象)
        Pagination pagination = ControllerHelper.getPagination(req_jsonObj);
        //从请求JSONObject对象中读取键“conditionList”对应的值(描述查询条件的JSONArray对象)
        List<Condition> conditionList = ControllerHelper.getConditions(req_jsonObj);
        //创建JSON对象message，以便往前端响应信息
        JSONObject message = new JSONObject();
        //在数据库表中增加对象
        try {
            if(pagination!=null&&conditionList!=null){
                //响应多个信息，其中conditionList, pagination两个对象引用为空是可能的
                this.responseGPs(response, conditionList, pagination);
            }
            else {
                //将课题的状态改为已提交
                graduateProjectToAdd.getGraduateProjectStatus().setId(1);
                graduateProjectToAdd.getGraduateProjectStatus().setDescription("已提交");
                System.out.println(graduateProjectToAdd);
                //添加到表中
                GraduateProjectCacheService.getInstance().update(graduateProjectToAdd);

                message.put("message", "提交成功");
                log.debug("增加成功");
            }
        }catch (SQLException e){
            message.put("message", "数据库操作异常");
            log.error(e.getMessage());
        }catch(Exception e){
            message.put("message", "网络异常");
            e.printStackTrace();
        }
        //响应message到前端
        response.getWriter().println(message);
    }

}